opencv |
您所在的位置:网站首页 › opencv 外轮廓 › opencv |
任务:给定这样一张图片求图片中白色区域的外接矩形、最小外接矩形、拟合多边形以及外接圆 x, y, w, h = cv2.boundingRect(points) 输入:点集返回值:左上角点坐标以及宽高实现代码: import cv2 imgpath = '1.jpg' # 读取图片 image = cv2.imread(imgpath) # 转换为灰度图 gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # 将图片二值化 _, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY) # 在二值图上寻找轮廓 contours, _ = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) for cont in contours: # 外接矩形 x, y, w, h = cv2.boundingRect(cont) # 在原图上画出预测的矩形 cv2.rectangle(image, (x, y), (x+w, y+h), (0, 0, 255), 10)输出结果: (cx,cy), (l,w), theta=cv2.minAreaRect(points) 输入:点集返回值:中心点坐标->(cx,cy);长宽->(l,w);从x轴逆时针旋转到宽(w)的角度->thetacv2.boxPoints()可以将minAreaRect的返回值转换为四个角点坐标实现代码: import cv2 imgpath = '1.jpg' image = cv2.imread(imgpath) gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) _, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY) contours, _ = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) for cont in contours: # 对每个轮廓点求最小外接矩形 rect = cv2.minAreaRect(cont) # cv2.boxPoints可以将轮廓点转换为四个角点坐标 box = cv2.boxPoints(rect) # 这一步不影响后面的画图,但是可以保证四个角点坐标为顺时针 startidx = box.sum(axis=1).argmin() box = np.roll(box,4-startidx,0) # 在原图上画出预测的外接矩形 box = box.reshape((-1,1,2)).astype(np.int32) cv2.polylines(image,[box],True,(0,255,0),10)输出结果: box = cv2.approxPolyDP(curve, epsilon, closed) 输入: curve:点集(折线图)epsilon:点到相对应的切线的距离的阈值。(大于阈值舍弃,小于阈值保留,epsilon越小,折线的形状越“接近”曲线。)closed:曲线是否闭合(True/False) 返回值: 多边形角点坐标实现代码: import cv2 imgpath = '1.jpg' image = cv2.imread(imgpath) gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) _, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY) contours, _ = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) for cont in contours: # 取轮廓长度的1%为epsilon epsilon = 0.01*cv2.arcLength(cont,True) # 预测多边形 box = cv2.approxPolyDP(cont,epsilon,True) img = cv2.polylines(image,[box],True,(0,0,255),10)输出结果: (x, y), radius = cv2.minEnclosingCircle(cont) 输入:点集返回值:圆心 --> (x, y), 半径 --> radius import cv2 image = cv2.imread('1.jpg') gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) _, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY) contours, _ = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) for cont in contours: # 外接圆 (x, y), radius = cv2.minEnclosingCircle(cont) cv2.circle(image,(int(x),int(y)),int(radius), (0, 0, 255), 10)输出结果: |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |